import 'dart:io';

import 'package:manager/exts/app_ext.dart';
import 'package:manager/exts/string_ext.dart';
import 'package:manager/http/dio_manager.dart';
import 'package:manager/http/urls.dart';
import 'package:common_ui/common_ui.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:get/get.dart';
import 'package:manager/configs/app_data.dart';
import 'package:image_picker/image_picker.dart';
import 'package:launch_app_store/launch_app_store.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';

import '../models/upgrade_model.dart';

///与android和ios通讯的service
///第三方插件方法操作
class PluginService extends GetxService {
  var CHANNEL_NAME = 'com.keyi.manager';
  late MethodChannel _methodChannel;
  ImagePicker? _imagePick;

  Future<PluginService> init() async {
    return this;
  }

  @override
  void onInit() {
    _methodChannel = MethodChannel(CHANNEL_NAME);
    super.onInit();
  }

  @override
  void onReady() {
    registerHandler();
    super.onReady();
    getVersion();
  }

  ///消息发送方法,通知android 和ios 需要实现的方法
  ///[method] 具体的逻辑,[args] 携带的参数
  Future<T?> invokeMethod<T>(String method, {dynamic args}) async {
    return await _methodChannel.invokeMethod(method, args);
  }

  ///注册信息通道,接收android和ios发送过来的数据
  ///根据[call.method]来判断具体的逻辑
  void registerHandler() {
    _methodChannel.setMethodCallHandler((call) async {
      switch (call.method) {
        case 'refreshOrder':
          break;
      }
    });
  }

  ///跳转应用市场
  Future<dynamic> toAppDetail() async {
    if (Platform.isAndroid) {
      return await _methodChannel.invokeMethod('toAppDetail');
    } else {
      await LaunchReview.launch(iOSAppId: '1391439719', writeReview: false);
    }
  }

  ///从相册选择图片
  Future<String?> selectPhoto() async {
    _imagePick ??= ImagePicker();
    var image = await _imagePick!.pickImage(source: ImageSource.gallery);
    return Future.value(image?.path);
  }

  ///使用相机拍照
  Future<String?> takePhoto() async {
    _imagePick ??= ImagePicker();
    var image = await _imagePick!.pickImage(source: ImageSource.camera);
    return Future.value(image?.path);
  }

  ///获取版本号
  void getVersion() async {
    var info = await PackageInfo.fromPlatform();
    AppData.appVersion = 'v${info.version}';
  }

  ///清除缓存
  Future<dynamic> clearCache() async {
    return await _methodChannel.invokeMethod('clearCache');
  }

  ///清除cookie
  Future<dynamic> clearCookie() async {
    return await _methodChannel.invokeMethod('clearCookie');
  }

  ///ios 跳转到appStore
  void intentAppStore() {
    _methodChannel.invokeMethod('intentAppStore');
  }

  ///跳转到系统浏览器
  void intentSystemBrowser(String url) {
    _methodChannel.invokeMethod('intentSystemBrowser', {'url': url});
  }

  void cpuInfo() async {
    await _methodChannel.invokeMethod('cpuInfo');
  }

  void upgrade({bool? toast}) async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    DioManager().request<UpgradeModel?>(Urls.upgrade, params: {
      "packageName": "com.foxconn.manager",
      "versionCode": packageInfo.buildNumber
    }, onSuccess: (data) {
      if (data != null) {
        upgradeDialog(data);
      } else if (toast ?? false) {
        showToast('已是最新版');
      }
    });
  }

  void upgradeDialog(UpgradeModel data) {
    showCustomDialog(
        title: '版本:${data.versionName}',
        Container(
          alignment: Alignment.topLeft,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SingleText(
                data.upgradeContent ?? '请尽快进行更新',
                padding: const EdgeInsets.only(left: 6, right: 6),
              )
            ],
          ),
        ),
        showCancel: !data.force,
        barrierDismissible: !data.force,
        confirmDismissible: !data.force, onConfirm: () {
      if (!(data.downloadUrl ?? '').isNullEmpty()) {
        launchUrl(Uri.parse(data.downloadUrl!));
      }
    });
  }
}
